package com.jcl.vertx.router;

import com.jcl.vertx.BaseRouter;
import io.vertx.core.Future;
import io.vertx.core.http.HttpServerResponse;
import io.vertx.ext.web.Route;
import io.vertx.ext.web.Router;

/**
 * 逐次调用router
 * 打印结果：
 *  route1
 *  route2
 *  route3
 */
public class UseNextRouter extends BaseRouter {
    @Override
    public void start(Future<Void> startFuture) throws Exception {
        router = Router.router(vertx);
        Route route = router.route("/some/path/");
        route.handler(ctx -> {
            HttpServerResponse response = ctx.response();
            // 开启分块响应，
            // 因为我们将在执行其他处理器时添加数据
            // 仅当有多个处理器输出时
            response.setChunked(true);
            response.write("route1\n");
            // 延迟5秒后调用下一匹配route
            ctx.vertx().setTimer(5000, tid -> ctx.next());
        });

        route.handler(ctx -> {
            HttpServerResponse response = ctx.response();
            response.write("route2\n");
            // 延迟5秒后调用下一匹配route
            ctx.vertx().setTimer(5000, tid -> ctx.next());
        });

        route.handler(ctx -> {
            HttpServerResponse response = ctx.response();
            response.write("route3");
            // 现在结束响应
            ctx.response().end();
        });

        vertx.createHttpServer().requestHandler(router).listen(8888, http -> {
            if (http.succeeded()) {
                startFuture.complete();
                System.out.println("HTTP server started on port 8888");
            } else {
                startFuture.fail(http.cause());
            }
        });
    }
}